<?php
/**
 * 用户模型
 * @date    2020-01-01
 * @author  kiro
 * @email   294843009@qq.com
 * @version 1.0
 */
/*

	/*
	 * All rights Reserved, Designed By www.youyacao.com <br>
	 * @Description:用户模型 <br>
	 * @version 蜻蜓C影视追剧系统  <br>
	 * @author:成都市一颗优雅草科技有限公司  <br>
	 * 注意：使用我司开源源代码请遵循license文件的协议仅供个人非盈利使用，禁止用于其他的商业用途
	 * 需要商业用途或者定制开发等可访问songshu.youyacao.com  联系QQ:2853810243 422108995 23625059584
	 * 正版系统查询系统 zhengbancha.youyacao.com
	 */
namespace App\Models;

use Dcat\Admin\Admin;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $table = 'users';

    protected $dateFormat = 'U';

    protected $casts = [
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'created_at' => 'datetime:Y-m-d H:i:s',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username',
        'phone',
        'email',
        'password',
        'avatar',
        'amount',
        'integral',
        'vip_end_time',
        'refcode',
        'truename',
        'qq',
        'avatar',
        'nickname',
        'desc',
        'sex',
        'birthday',
        'alipay_account_name',
        'alipay_account',
        'pid',
        'is_auth',
        'is_audio',
        'last_login_time',
        'share_free_num',
        'status'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'api_token',
        'wx_openid',
        'qq_openid',
        'wb_openid',
        'is_admin',
        'is_super'
    ];

    public static function resetPass($username, $password)
    {
        return self::where('username', $username)->update([
            'password' => bcrypt($password)
        ]);
    }

    public static function getRefNum($user_id)
    {
        $key = 'my_ref_num_'.$user_id;
        $num = cache($key);
        if (empty($num)){
            $num = self::where('pid', $user_id)->count();
            cache([$key => $num], mt_rand(10,30));
        }
        return $num;
    }



    public static function setUsername($id)
    {
        $username = getRandNumber();
        if (self::where('username', $username)->exists()) {
            self::setUsername($id);
        } else {
            return self::where('id', $id)->update(['username' => $username]);
        }
    }

    /**
     * 操作账户金额
     */
    public static function amount($user_id, $amount = 0, $remark = '', $source = 'AGENT_RECHARGE')
    {
        if ($amount > 0) {
            $result = self::where('id', $user_id)->increment('amount', abs($amount));
            if (!$result) {
                throw new \Exception('增加余额失败');
            }
        } else {
            $user = self::where('id', $user_id)->first();
            if ($user->amount < abs($amount)) {
                throw new \Exception('余额不足');
            }
            $result = self::where('id', $user_id)->decrement('amount', abs($amount));
            if (!$result) {
                throw new \Exception('扣除余额失败');
            }
        }
        UserAccountLog::create([
            'user_id'   => $user_id,
            'type'      => UserAccountLog::TYPE_AMOUNT,
            'amount'    => $amount,
            'source'    => $source,
            'remark'    => $remark,
            'status'    => 1,
        ]);
        return $result;
    }

    /**
     * 操作积分
     */
    public static function integral($user_id, $integral = 0, $remark = '', $source = 'AGENT_RECHARGE')
    {
        if ($integral > 0) {
            $result = self::where('id', $user_id)->increment('integral', abs($integral));
            if (!$result) {
                throw new \Exception('增加爽豆失败');
            }
        } else {
            $user = self::where('id', $user_id)->first();
            if ($user->integral < abs($integral)) {
                throw new \Exception('爽豆不足');
            }
            $result = self::where('id', $user_id)->decrement('integral', abs($integral));
            if (!$result) {
                throw new \Exception('扣除爽豆失败');
            }
        }
        UserAccountLog::create([
            'user_id'   => $user_id,
            'type'      => UserAccountLog::TYPE_INTEGRAL,
            'integral'  => $integral,
            'source'    => $source,
            'remark'    => $remark,
            'status'    => 1,
        ]);
        return $result;
    }

    /**
     * 操作金币
     */
    public static function gold($user_id, $gold = 0, $remark = '', $source = 'AGENT_RECHARGE')
    {
        if ($gold > 0) {
            $result = self::where('id', $user_id)->increment('gold', abs($gold));
            if (!$result) {
                throw new \Exception('增加金币失败');
            }
        } else {
            $user = self::where('id', $user_id)->first();
            if ($user->gold < abs($gold)) {
                throw new \Exception('金币不足');
            }
            $result = self::where('id', $user_id)->decrement('gold', abs($gold));
            if (!$result) {
                throw new \Exception('扣除金币失败');
            }
        }
        UserAccountLog::create([
            'user_id'   => $user_id,
            'type'      => UserAccountLog::TYPE_GOLD,
            'gold'      => $gold,
            'source'    => $source,
            'remark'    => $remark,
            'status'    => 1,
        ]);
        return $result;
    }

    public static function addConsume($user_id, $mps_id, $v_id, $sort, $price)
    {
        Consume::create([
            'user_id' => $user_id,
            'mps_id' => $mps_id,
            'video_id' => $v_id,
            'sort' => $sort,
            'price' => $price,
            'status' => 1,
        ]);
    }

    public function department()
    {
     return $this->hasOne(Department::class, 'id', 'department_id');
    }

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    //添加消费记录

    //访问器avatar，获取头像，没有值的时候默认一个头像
    public function getAvatarAttribute($value): string
    {
        return $value ?: env('APP_URL').'/uploads/avatar.png';
    }
    //访问器username，获取用户名，没有值的时候默认一个用户名，用户名是固定的‘用户’+email的@前的值
    public function getUsernameAttribute($value): string
    {
        return $value ?: 'user'.explode('@',$this->email)[0];
    }
    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }

    public function consume()
    {
        return $this->hasMany(Consume::class);
    }

    public function mps()
    {
        return $this->hasOne(Mp::class, 'id', 'mps_id');
    }
    public function TposInfo()
    {
        return $this->hasOne(TposInfo::class,'openid','wx_openid');
    }

    public function yuyueinfo()
    {
        return $this->hasMany(ReservationRecord::class);
    }

    public function order()
    {
        return $this->hasMany(Order::class);
    }
    //我的追剧
    public function traces()
    {
        return $this->hasManyThrough(Episode::class,Trace::class,'user_id','id','id','episodes_id');
    }
    //我的喜欢
    public function like()
    {
        return $this->hasManyThrough(Episode::class,Like::class,'user_id','id','id','episodes_id');
    }
    //历史播放记录
    public function history()
    {
        return $this->hasManyThrough(Episode::class,History::class,'user_id','id','id','traces_id');
    }
    //签到记录
    public function checking()
    {
        return $this->hasMany(Checkin::class);
    }
    //积分
    public function integrate()
    {
        return $this->hasMany(Integrate::class);
    }

    public function ask()
    {
        return $this->hasMany(Ask::class, 'pid', 'id');
    }

    public function userCard()
    {
        return $this->hasOne(UserCard::class, 'user_id', 'id');
    }

}
